package com.example.clientchat;

import java.io.*;
import java.net.*;

import android.app.*;
import android.content.*;
import android.os.*;
import android.util.*;
import android.view.*;
import android.widget.*;

public class ClientChatActivity extends TabActivity {//탭 액티비티로부터 상속
	private String str;
    private Socket socket=null;
    private String msg=null;
    private BufferedReader reader;
    private PrintWriter writer;
    String ip=null; // IP
    int port; // PORT번호
    EditText et,setip,setport;
    TextView tv,tv2,tv3,tv4,tv5;
    Button btn;
    TabHost mTab;
    
    
	
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        TabHost mTab = getTabHost();//탭 호스트 객체 생성 안에 FrameLayout 배치
        LayoutInflater inflater = LayoutInflater.from(this);//TAP설정 
        inflater.inflate(R.layout.main, mTab.getTabContentView(), true);//Tap설정
        
        mTab.addTab(mTab.newTabSpec("tag").setIndicator("TCP/IP").setContent(R.id.linearLayout2));//chat 부분 탭
        mTab.addTab(mTab.newTabSpec("tag").setIndicator("Setting").setContent(R.id.linearLayout3));//세팅부분탭
        mTab.addTab(mTab.newTabSpec("tag").setIndicator("PowerControl").setContent(R.id.linearLayout5));//버튼 부분 탭
        
        //각 버튼 리스너 등록
        et = (EditText) findViewById(R.id.editText01);
        setip = (EditText) findViewById(R.id.setIp);
        setport = (EditText) findViewById(R.id.PortEdit);
        tv = (TextView) findViewById(R.id.textView01);
        tv2 = (TextView) findViewById(R.id.textView02);
        tv3 = (TextView) findViewById(R.id.textView03);
        tv4 = (TextView) findViewById(R.id.textView3);
        tv5 = (TextView) findViewById(R.id.TextView01);
    	//뷰어쓰레드 실행
    	tv4.setText(ip+"ip입력하세요.");	
     
    }//oncreat 종료
	
	/*private Thread checkUpdate = new Thread() {
        public void run() {
            try {
                String line;
                Log.w("ChattingStart", "Start Thread");
                while (true) {
 
                    Log.w("Chatting is running", "chatting is running");
                    line = reader.readLine();
                    html = line;
                    mHandler.post(showUpdate);
                }
 
            } catch (Exception e) {
            }
        }
    };
 
    private Runnable showUpdate = new Runnable() {
        public void run() {
            Toast.makeText(ClientChatActivity.this, "Coming word: " + html,
                    Toast.LENGTH_SHORT).show();
            tv2.setText("되돌아옴."+html);
        }
    };*/
	
	//SenderThread 시작 
    public void btnOnclick(View v) {
    	Intent intent;
    	switch(v.getId()){
    	case R.id.sendBtn:
    		tv2.setText("시작합니다.");
		
    		// TODO Auto-generated method stub
    		msg= et.getText().toString();//chat 탭에서 텍스트 얻어옴
    		try{
    			writer =
    					new PrintWriter(socket.getOutputStream());//아웃풋버퍼스트림생성
    			
			
					if(msg!=""){
						tv2.setText("보내는중,.....");
						if (msg.equals("exit")){
						
						}
						writer.println(msg);//라이터 스트림에 msg 적제
						writer.flush();//스트림 출력 >서버로 보낸다는말	
						msg=null;//메시지 초기화
						et.setText("");//에딧택스트 초기화
						tv2.setText("보내기 완료!!,.....");
						
						//tv2.setText("보내기 완료!!,....."+str);//인풋스트림 오는 거 확실히 확인
					
					}
			
			
    		}
    		catch (Exception e){
    			//tv3.setText(e.getMessage());
    		}
    		//SocketChat stringstr = new SocketChat();//서비스에서 스트링값 받아오기??
    		//String str2 = stringstr.str;
    		//tv3.setText(str2);
    		break;
    	case R.id.connectionBtn:
    		try {
    			tv.setText(ip+","+port+" setting");
    			socket = new Socket(ip,port);
    		} catch(Exception e){
    			tv3.setText(e.getMessage());
    		}
    		tv2.setText("소켓 세팅완료");
    		intent = new Intent(this,SocketChat.class);
    		//startService(intent);
    		tv3.setText("thread 시작");
    		Thread rcv = new ReceiverThread(socket);//뷰어스레드 생성
        	rcv.start();
        	//rcv.setDaemon(true);//강제종료됨
    		break;
    	case R.id.disconnectioBtn:
    		try {
    			writer.println("AT+byby");//라이터 스트림에 msg 적제
				writer.flush();
    			intent = new Intent(this,SocketChat.class);
        		//stopService(intent);//서비스 종료
				socket.close();
				
			} catch (Exception e) {
				// TODO Auto-generated catch block
				
			}
    		break;
    	case R.id.ipSetBtn:
    		ip = setip.getText().toString();
    		tv4.setText(ip+" 세팅완료");
    		setip.setText("");
			
    		break;
    	case R.id.PortBtn:
    		String port1 =setport.getText().toString();
    		port = Integer.parseInt(port1);
    		tv5.setText(port1+" 세팅완료");
    		setport.setText("");
			
    		break;
		//Thread thread1 = new SenderThread(socket);
		//thread1.start();
		//thread1.setDaemon(true);
    	}
	}
    class ReceiverThread extends Thread {
		Socket socket;

		ReceiverThread(Socket socket) {
			super();
			this.socket = socket;
		}
		public void run(){
			
			try{
				
				reader = new BufferedReader(
						new InputStreamReader(socket.getInputStream()));
				while(true){
					
					str = reader.readLine();//인풋스티림으로부터 값 읽기
					if(str == null){
						break;
					}
					Log.i("demo", "ServiceRecieve"); //데이터값 받아오면 로그값 찍음
					mHandler.sendEmptyMessage(0);							
			    	Thread.sleep(200);
					
				
				}
				
			}
			catch(Exception e){
				//tv3.setText(e.getMessage());
			}
		}

	}//RecieverThread 종료
	
	Handler mHandler = new Handler(){
		public void handleMessage(Message msg){
			if(msg.what ==0){
				tv2.setText("수신!!!,....."+str);
			}
			
		}
	};

	
	
	
 

}




